package cn.com.yxw.webapp.controller;

import cn.com.yxw.webapp.pojo.Admin;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/5/24.
 */
public class UserListPDFView extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Content-Disposition", "inline; filname=" + new String("用户列表".getBytes(), "iso8859-1"));
        List<Admin> adminList = (List<Admin>) model.get("list");
        Table table = new Table(3);
        table.setWidth(80);
        table.setBorder(1);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        //使用中文的字体
        BaseFont cnBaseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        Font font = new Font(cnBaseFont, 10, Font.NORMAL, Color.BLUE);
        table.addCell(buildFontCell("账号", font));
        table.addCell(buildFontCell("姓名", font));
        table.addCell(buildFontCell("密钥", font));
        for (Admin admin : adminList) {
            table.addCell(admin.getUsername());
            table.addCell(admin.getPassword());
            table.addCell(admin.getKey());
        }
        document.add(table);
    }

    private Cell buildFontCell(String content, Font font) throws RuntimeException{
        try {
            Phrase phrase = new Phrase(content, font);
            return new Cell(phrase);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
